import { getCategoryTopAPI } from '@/services/category'
import { getHomeBannerAPI } from '@/services/home'
import type { CategoryTopItem } from '@/types/category'
import type { BannerItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'

const useCategoryHooks = () => {
  // 轮播图数据
  const bannerList = ref<BannerItem[]>([])
  // 分类列表数据
  const categoryList = ref<CategoryTopItem[]>([])
  // 激活索引
  const activeIndex = ref(0)

  // 获取轮播图数据
  const getBannerData = async () => {
    const res = await getHomeBannerAPI(2)
    bannerList.value = res.result
  }

  // 获取分类列表数据
  const getCategoryTopData = async () => {
    const res = await getCategoryTopAPI()
    categoryList.value = res.result
  }

  // 是否数据加载完毕
  const isFinish = ref(false)
  // 页面加载
  onLoad(async () => {
    await Promise.all([getBannerData(), getCategoryTopData()])
    isFinish.value = true
  })

  // 提取当前二级分类数据
  const subCategoryList = computed(() => {
    return categoryList.value[activeIndex.value]?.children || []
  })

  return { isFinish, categoryList, activeIndex, bannerList, subCategoryList }
}
export default useCategoryHooks
